package band.wukong.practice.barcode.zxing;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
 * As you see...
 *
 * @author wukong(wukonggg@139.com)
 */
public class BarcodeTool {

    private static final String CHARSET_DEFAULT = "UTF-8";

    public static void encode(String content, BarcodeFormat fmt
        , int width, int height
        , Path imgPath, String imgFormat) {
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET_DEFAULT);

        BitMatrix byteMatrix = null;
        try {
            byteMatrix = new MultiFormatWriter()
                .encode(content, fmt, width, height, hints);
        } catch (WriterException e) {
            throw new RuntimeException(e);
        }
        try {
            MatrixToImageWriter.writeToPath(byteMatrix, imgFormat, imgPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String decode(File image) {
        BufferedImage img = null;
        try {
            img = ImageIO.read(image);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        LuminanceSource source = new BufferedImageLuminanceSource(img);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
        Map<DecodeHintType, Object> hints = new HashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET_DEFAULT);

        Result result = null;
        try {
            result = new MultiFormatReader().decode(binaryBitmap, hints);
        } catch (NotFoundException e) {
            throw new RuntimeException(e);
        }
        return result != null ? result.getText() : "";

    }

    @Deprecated
    private static void generate2DCode(String content) throws WriterException, IOException {
        final Integer ZXING_2D_BARCODE_WIDTH = 180;
        final Integer ZXING_2D_BARCODE_HEIGHT = 160;

        Map<EncodeHintType, String> map = new HashMap<EncodeHintType, String>();
        map.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix byteMatrix = new MultiFormatWriter()
            .encode(content, BarcodeFormat.QR_CODE, ZXING_2D_BARCODE_WIDTH,
                ZXING_2D_BARCODE_HEIGHT, map);
        FileSystem fileSystem = FileSystems.getDefault();
        Path path = fileSystem.getPath("D:/qrCode.png");
        MatrixToImageWriter.writeToPath(byteMatrix, "png", path);
    }


}
